package com.base.component.ai.platform.prompt;

import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.base.component.ai.agent.bo.ContextParamBO;
import com.base.component.ai.agent.bo.PromptConfigBO;
import com.base.component.ai.agent.core.prompt.PromptHandler;
import com.base.component.ai.platform.FillStrategyHandler;
import com.base.component.ai.platform.core.bo.common.ChatCompletionsBO;
import com.base.component.ai.platform.core.bo.common.ChatCompletionsLogBO;
import com.base.core.head.constants.MdcConstants;
import com.base.core.head.dto.ai.MessageBaseDTO;
import com.gitee.magic.context.ConverterEditorUtils;
import com.gitee.magic.core.json.JsonObject;
import com.gitee.magic.core.utils.StringUtils;

@Service
public abstract class PromptBaseService<C extends ContextParamBO,P,M extends MessageBaseDTO> {
	
	private Class<M> prototype;
	
	public PromptBaseService(Class<M> cls) {
		this.prototype=cls;
	}

	@Autowired
	private PromptHandler promptHandler;
	@Autowired
	private FillStrategyHandler<C> fillStrategyHandler;
	@Autowired
	private PromptTemplateService<M> promptTemplateService;
	
	public ChatCompletionsBO<M> getChatCompletionsParam(C context,P param,String code) {
		PromptConfigBO promptConfig =promptHandler.loadPrompt(code, context.getLanguage());
		ChatCompletionsBO<M> ccb=new ChatCompletionsBO<>();
		ccb.setRequestId(MDC.get(MdcConstants.REQUESTID));
		ccb.setCode(promptConfig.getCode());
		if(!StringUtils.isEmpty(context.getConversationId())) {
			ccb.setConversationId(context.getConversationId()+"_"+code);
		}
		ccb.setModel(promptConfig.getModelName());
		ccb.setTemperature(promptConfig.getTemperature());
		ccb.setSystemPrompt(fillStrategyHandler.fill(code, promptConfig.getSystemPrompt(), param,context));
		ccb.setUserPrompt(fillStrategyHandler.fill(code, promptConfig.getUserPrompt(), param,context));
		ccb.setResponseFormat(promptConfig.getResponseFormat());
		ccb.setPayload(new JsonObject());
		ccb.setChatCompletionsLog(new ChatCompletionsLogBO(
				ConverterEditorUtils.converter(param, JsonObject.class),
				promptConfig.getUserPrompt(),
				promptConfig.getSystemPrompt()));
		return ccb;
	}
	
	public String execute(C context,P param,String code) {
		ChatCompletionsBO<M> ccb=getChatCompletionsParam(context,param,code);
		return promptTemplateService.execute(ccb,getPrototype());
	}
	
	public <T>T execute(C context,P param,String code,Class<T> prototype) {
		String content=execute(context,param,code);
		return ConverterEditorUtils.restoreObject(prototype, new JsonObject(content));
	}

	public Class<M> getPrototype() {
		return prototype;
	}
}
